package exec;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

class StreamLogHandler extends Thread {
	/**
	 * buffer being read
	 */
	private BufferedReader bufferedReader = null;
	private StringBuffer outBuf;
	/**
	 * name of the file being writed
	 */
	private String strOutFileName = null;

	/**
	 * @param m_stream
	 * @param name
	 */
	public StreamLogHandler(InputStreamReader m_stream, String name, StringBuffer logBuf) {
		super();
		strOutFileName = name;
		outBuf = logBuf;
		bufferedReader = new BufferedReader(m_stream);
	}

	/**
	 * Stream the data.
	 */
	public void run() {
		/*
		 * open the output log file
		 */
		FileOutputStream output = null;
		if(strOutFileName != null){
			try {
				output = new FileOutputStream(strOutFileName);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
				return;
			}			
		}

		/*
		 * reading and writing
		 */
		String inc = null;
		byte[] bt = null;
		try {
			while ((inc = bufferedReader.readLine()) != null) {
				if(strOutFileName == null){
					if(outBuf == null)System.out.println(inc);
					else outBuf.append(inc + "\r\n");
				}
				else {
					bt = inc.getBytes();
					output.write(bt);
					output.write('\n');
				}
			}
		} catch (IOException ioe) {
			System.out.println("error");
		}
		/*
		 * flush the file
		 */
		if(strOutFileName != null){
			try {
				output.flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		/*
		 * close the file
		 */
		if(strOutFileName != null){
			try {
				output.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
}
